package com.chanjiedata.changbs.module.mine;

/**
 * 文件名 : TiXianActivity
 * 创建者 : MangoWang
 * 创建日期 : 2019/11/28 21:25
 * 微信 : MangoWaWang
 * 邮箱 : 763482205@qq.com
 * 描述 : TODO
 */


import android.content.Intent;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.Gravity;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.chanjiedata.changbs.R;
import com.chanjiedata.changbs.base.BaseActivity;
import com.chanjiedata.changbs.net.Apis;
import com.chanjiedata.changbs.net.NetworkManager;
import com.chanjiedata.changbs.net.WebApis;
import com.chanjiedata.changbs.net.interfaces.OnRequestCallBack;
import com.chanjiedata.changbs.proto.Connect;
import com.chanjiedata.changbs.proto.Index;
import com.chanjiedata.changbs.proto.MemberBank;
import com.chanjiedata.changbs.proto.Recharge;
import com.chanjiedata.changbs.utlis.GsonUtils;
import com.chanjiedata.changbs.utlis.InputMethodUtils;
import com.chanjiedata.changbs.utlis.MoneyTextWatcher;
import com.chanjiedata.changbs.utlis.StatusBarUtil;
import com.chanjiedata.changbs.utlis.StringUtil;
import com.chanjiedata.changbs.view.pswkeyboard.widget.PopEnterPassword;
import com.chanjiedata.changbs.view.pswkeyboard.widget.PopPayEnterPassword;
import com.chanjiedata.changbs.web.ui.WebViewActivity;
import com.google.protobuf.InvalidProtocolBufferException;
import com.ruffian.library.widget.RRelativeLayout;

import java.text.DecimalFormat;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TiXianActivity extends BaseActivity implements MoneyTextWatcher.CountAccountAndChargeInterface {
    @BindView(R.id.back_tv)
    TextView backTv;
    @BindView(R.id.tv_title)
    TextView tvTitle;
    @BindView(R.id.tv_bank_card_name)
    TextView tvBankCardName;
    @BindView(R.id.rl_bank_card)
    RRelativeLayout rlBankCard;
    @BindView(R.id.et_money)
    EditText etMoney;
    @BindView(R.id.tv_balance)
    TextView tvBalance;
    @BindView(R.id.tv_quan_bu_ti_xian)
    TextView tvQuanBuTiXian;
    @BindView(R.id.ll_quan_bu_ti_xian)
    LinearLayout llQuanBuTiXian;
    @BindView(R.id.tv_account_money)
    TextView tvAccountMoney;
    @BindView(R.id.ll_shou_xun_fei)
    LinearLayout llShouXunFei;
    @BindView(R.id.bt_ti_xian)
    Button btTiXian;
    @BindView(R.id.cb_check)
    CheckBox cbCheck;
    @BindView(R.id.tv_xie_yi)
    TextView tvXieYi;
    @BindView(R.id.ll_xie_yi)
    LinearLayout llXieYi;
    private float balance = 0;
    private String card_id;
    private String mpassword;
    public static int GOTOBANKlIST = 100;
    public static int BACKTOWITHDRAW = 200;
    private MemberBank.bank bankCardBean;
    private String yu_er;
    private PopEnterPassword popEnterPassword;  // 支付密码
    private PopPayEnterPassword popEnterPasswordNext;  // 验证码
    private String pd_cash_service_charge = "0";
    private String single_pd_cash_price = "0";
    private String cb_xie_yi = "1";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_ti_xian);
        ButterKnife.bind(this);
        StatusBarUtil.setStatusBarLightMode(this, Color.parseColor("#F2F3F5"), true);
        tvTitle.setText("提现");
        yu_er = getIntent().getStringExtra("yu_er");
        tvBalance.setText("余额 ¥ " + yu_er);
        balance = Float.valueOf(yu_er);
        loadView();
        initListener();
        loadSettingInfo();

        popEnterPassword = new PopEnterPassword(this, etMoney.getText().toString(), "", "提现", password -> {
            Connect.sms_register.Builder builder = Connect.sms_register.newBuilder();
            builder.setPayword(password);
            showProgress();
            NetworkManager.INSTANCE.post(Apis.check_pd_pwd2, builder.build().toByteArray(), new OnRequestCallBack() {
                @Override
                public void onOk(byte[] response) {

                }

                @Override
                public void onError(int errorCode, String errorMessage) {
                    hideProgress();
                    if (errorCode == 200) {
                        mpassword = password;
                        // 显示窗口
                        popEnterPasswordNext.showAtLocation(TiXianActivity.this.findViewById(R.id.tv_balance),
                                Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                        popEnterPassword.dismiss();
                    } else {
                        popEnterPassword.pwdView.cleanKeyNumber();
                        showToast(errorMessage);

                    }
                }
            });


        });

        popEnterPasswordNext = new PopPayEnterPassword(this, password -> {
            showProgress();
            Recharge.Pd_cash_add.Builder builder = Recharge.Pd_cash_add.newBuilder();
            builder.setCaptcha(password).setPassword(mpassword)
                    .setCardId(card_id).setPdcAmount(etMoney.getText().toString())
                    .setIsCashAgreement(cb_xie_yi);
            NetworkManager.INSTANCE.post(Apis.post_tixian, builder.build().toByteArray(), new OnRequestCallBack() {
                @Override
                public void onOk(byte[] response) {

                }

                @Override
                public void onError(int errorCode, String errorMessage) {
                    hideProgress();
                    if (errorCode == 200) {
                        String cardName = tvBankCardName.getText().toString();
                        String price = etMoney.getText().toString();
                        String ping = "?cardName=" + cardName + "&price=" + price + "&single_pd_cash_price=" + single_pd_cash_price;
                        WebViewActivity.startActivity(mContext, WebApis.progress + ping);
                    } else {
                        showToast(errorMessage);
                    }
                    finish();
                }
            });
        });


    }

    private void loadSettingInfo() {
        NetworkManager.INSTANCE.post(Apis.setting_info, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                pd_cash_service_charge = Index.Get_pd_cash_setting_info.parseFrom(response).getPdCashServiceCharge();
                single_pd_cash_price = Index.Get_pd_cash_setting_info.parseFrom(response).getSinglePdCashPrice();
                cb_xie_yi = Index.Get_pd_cash_setting_info.parseFrom(response).getIsCashAgreement();
                tvXieYi.setText(Index.Get_pd_cash_setting_info.parseFrom(response).getTitleCashAgreement());
                switch (cb_xie_yi) {
                    case "0":
                        llXieYi.setVisibility(View.GONE);
                        break;
                    case "1":
                        cbCheck.setChecked(true);
                        cbCheck.setEnabled(false);
                        llXieYi.setVisibility(View.VISIBLE);
                        break;
                    case "2":
                        cbCheck.setChecked(false);
                        cbCheck.setEnabled(true);
                        llXieYi.setVisibility(View.VISIBLE);
                        break;
                }

            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    private void initListener() {
        tvQuanBuTiXian.setOnClickListener(view -> {
            etMoney.setText(yu_er);
        });

        rlBankCard.setOnClickListener(view -> {
            Intent intent = new Intent(mContext, BankCardActivity.class);
            intent.putExtra("type", 1);
            startActivityForResult(intent, GOTOBANKlIST);
        });
        btTiXian.setOnClickListener(view -> submit());
        backTv.setOnClickListener(view -> finish());
        //默认两位小数
        etMoney.addTextChangedListener(new MoneyTextWatcher(etMoney, this));
        tvXieYi.setOnClickListener(v -> {
            WebViewActivity.startActivity(mContext, WebApis.WithdrawalAgreement);
        });
        cbCheck.setOnCheckedChangeListener((compoundButton, isChecked) -> {
            if (isChecked) {
                cb_xie_yi = "1";
            } else {
                cb_xie_yi = "2";
            }
        });
    }

    /**
     * 加载银行卡数据
     */
    private void loadView() {
        NetworkManager.INSTANCE.post(Apis.member_bank, new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) throws InvalidProtocolBufferException {
                bankCardBean = MemberBank.get_bank.parseFrom(response).getArrayList().get(0);
                // 选中第一个银行卡
                String bank_card = bankCardBean.getBankCard();
                bank_card = bank_card.substring(bank_card.length() - 4);
                tvBankCardName.setText(bankCardBean.getBankName() + " (" + bank_card + ")");
                card_id = bankCardBean.getCardId() + "";
            }
            @Override
            public void onError(int errorCode, String errorMessage) {
                showToast(errorMessage);
            }
        });
    }

    /**
     * 提交银行卡数据
     */
    private void submit() {
        InputMethodUtils.hideSoftInput(this);
        String money = etMoney.getText().toString();
        boolean empty = TextUtils.isEmpty(money);
        if (empty) {
            showToast("请先输入提现金额");
            return;
        }
        Recharge.Pd_cash_add.Builder builder = Recharge.Pd_cash_add.newBuilder();
        builder.setPdcAmount(money);
        builder.setIsCashAgreement(cb_xie_yi);
        NetworkManager.INSTANCE.post(Apis.check_cash, builder.build().toByteArray(), new OnRequestCallBack() {
            @Override
            public void onOk(byte[] response) {
            }

            @Override
            public void onError(int errorCode, String errorMessage) {
                if (errorCode == 200) {
                    // 显示窗口
                    popEnterPassword.showAtLocation(TiXianActivity.this.findViewById(R.id.tv_balance),
                            Gravity.BOTTOM | Gravity.CENTER_HORIZONTAL, 0, 0); // 设置layout在PopupWindow中显示的位置
                } else {
                    showToast(errorMessage);
                }

            }
        });
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        // TODO Auto-generated method stub
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == GOTOBANKlIST && resultCode == BACKTOWITHDRAW) {
            String infoString = data.getStringExtra("info");
            bankCardBean = GsonUtils.jsonToBean(infoString, MemberBank.bank.class);
            // 选中第一个银行卡
            String bank_card = bankCardBean.getBankCard();
            bank_card = bank_card.substring(bank_card.length() - 4);
            tvBankCardName.setText(bankCardBean.getBankName() + " (" + bank_card + ")");
            card_id = bankCardBean.getCardId() + "";
        }
    }

    @Override
    public void afterTextChang(String s) {
        if (TextUtils.isEmpty(s)) {
            llQuanBuTiXian.setVisibility(View.VISIBLE);
            llShouXunFei.setVisibility(View.GONE);
        } else {
            llQuanBuTiXian.setVisibility(View.GONE);
            llShouXunFei.setVisibility(View.VISIBLE);
            DecimalFormat decimalFormat = new DecimalFormat("0.00");
            Double percentage = Double.valueOf(pd_cash_service_charge);
            Double monye = Double.valueOf(s);
            double c = monye * percentage;
            String cc1 = StringUtil.calculateProfit(c);
            Double aDouble = Double.valueOf(cc1);
            Log.e("songwang", "afterTextChang: " + c);
            StringBuilder text = new StringBuilder();
            if (c > 0) {
                text.append("扣除 ¥ " + cc1 + "服务费");
            }
            Double charge = Double.valueOf(single_pd_cash_price);
            if (charge > 0) {
                text.append(" 手续费 ¥ " + StringUtil.calculateProfit(charge));
            }
            double v = monye - aDouble - charge;
            if (v > 0) {
                text.append(" 实际到账金额 ¥ " + StringUtil.calculateProfit(v));
            }
            tvAccountMoney.setText(text.toString());
        }
    }


}
